import { component } from "components/common/component";
import React = require("react");
import { SpinerComponent, State as SpinerState } from "components/common/spiner-component";
import * as chitu from "maishu-chitu";
import { ShoppingService } from "mobile/services/shoppingService";
import { buttonOnClick } from "maishu-ui-toolkit";

export interface StoreCouponsState extends SpinerState {
    coupons: Coupon[]
}

@component()
export class StoreCoupons extends SpinerComponent<{}, StoreCouponsState> {
    shopping: ShoppingService;
    constructor(props) {
        super(props);
        this.shopping = this.createService(ShoppingService);
    }
    async loadData() {
        let coupons = await this.shopping.storeCoupons();
        return { coupons };
    }
    render() {
        let { coupons } = this.state;
        return <>
            {coupons.length > 0 ?
                <hr />
                :
                <div className="norecords">
                    <div className="icon">
                        <i className="icon-money">

                        </i>
                    </div>
                    <h4 className="text">暂无可领取的优惠券</h4>
                </div>
            }
            {coupons.map(o =>
                <div key={o.Id}>
                    <CouponControl page={this.page} coupon={o} />
                    <hr />
                </div>
            )}
        </>
    }
}

export class CouponControl extends React.Component<{ coupon: Coupon, page: chitu.Page }, any> {
    receiveCoupon(coupon: Coupon): Promise<any> {
        let shopping = this.props.page.createService(ShoppingService);
        return shopping.receiveCoupon(coupon.Id);
    }
    private formatDate(date: Date) {
        let d = date as Date;
        let mm = d.getMonth() + 1;
        let dd = d.getDate();

        return `${mm < 10 ? '0' + mm : mm}/${dd < 10 ? '0' + dd : dd}`;
    }
    render() {
        let o = this.props.coupon;
        return <div className="coupon">
            <button className={`pull-right receive available`}
                ref={(btn: HTMLButtonElement) => {
                    if (!btn) return;

                    buttonOnClick(btn,
                        () => {
                            return this.receiveCoupon(o);
                        },
                        { toast: '领取优惠劵成功' }
                    )
                }}>
                立即领取
            </button>
            <div className="main">
                <div>
                    ￥{o.Discount}
                </div>
                <div className="date">
                    {`有效期 ${o.ValidBegin ? this.formatDate(o.ValidBegin) : ''} 至 ${o.ValidEnd ? this.formatDate(o.ValidEnd) : ''}`}
                    <div>
                        {o.Amount ? <span>满{o.Amount}元可以使用</span> : <span>任意金额可用使用</span>}
                    </div>
                </div>
            </div>
        </div>
    }
}